package com.credithc.eagleeye.plugins.rabbitmq;
import com.credithc.eagleeye.thread.EagleEyeThreadContext;
import com.credithc.eagleeye.thread.TraceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;

import java.util.Map;

import static com.credithc.eagleeye.constants.EagleEyeConstant.HC_RPC_ID;
import static com.credithc.eagleeye.constants.EagleEyeConstant.HC_TRACE_ID;
/**
 * 描 述: <br/>
 * 作 者: zhangjin<br/>
 * 创 建：2019年10月24日<br/>
 * 版 本：v1.0.0<br>
 * <p>
 * 历 史: (版本) 作者 时间 注释 <br/>
 */
@Slf4j
public class EagleEyeBeforePublishPostProcessor implements MessagePostProcessor {
    @Override
    public Message postProcessMessage(Message message) throws AmqpException {
        try {
            //在aop时已经填充了TraceInfo，理论上这里不应该为null
            TraceInfo traceInfo = EagleEyeThreadContext.getTraceInfo();
            if (traceInfo == null) {
                traceInfo=new TraceInfo();
            }
            MessageProperties messageProperties = message.getMessageProperties();
            Map<String, Object> headers = messageProperties.getHeaders();
            headers.put(HC_TRACE_ID, traceInfo.getTraceId());
            headers.put(HC_RPC_ID, traceInfo.getRpcId());
        } catch (Exception e) {
        }
        return message;
    }

}
